package com.icarsaas.saas.tenant.system.web;

import com.icarsaas.saas.common.utils.ResultVoUtil;
import com.icarsaas.saas.common.utils.SpringContextUtil;
import com.icarsaas.saas.common.vo.ResultVo;
import com.icarsaas.saas.component.fileUpload.FileUploadUtil;
import com.icarsaas.saas.component.fileUpload.config.properties.UploadProjectProperties;
import com.icarsaas.saas.tenant.system.model.FileUpload;
import com.icarsaas.saas.tenant.system.service.UploadService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;

@Controller @Api(tags="附件模块") @RequestMapping(value = "/file/") @Slf4j
public class UploadController {

    @Autowired private UploadService uploadService;
    /**
     * 上传web格式图片
     */
    @PostMapping("/upload/file") @ResponseBody
    public ResultVo<?> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("refId") String refId
            , @RequestParam("type") String type, @RequestParam("path") String path) {
        // 创建Upload实体对象
        if (StringUtils.isEmpty(path)) path = "/file";
        FileUpload upload = FileUploadUtil.getFile(file, refId, type, path);
        log.info("附件信息：RefId={}, type={}, path={}", refId, type, path);
        try {
            return saveFile(file, upload);
        } catch (IOException | NoSuchAlgorithmException e) {
            return ResultVoUtil.error("上传图片失败");
        }
    }
    /**
     * 上传web格式头像
     */
    @PostMapping("/upload/picture") @ResponseBody
    public ResultVo<?> uploadPicture(@RequestParam("picture") MultipartFile multipartFile, @RequestParam("refId") String refId) {
        // 创建Upload实体对象
        FileUpload upload = FileUploadUtil.getFile(multipartFile, refId,"","/avatar");
        try {
            return saveFile(multipartFile, upload);
        } catch (IOException | NoSuchAlgorithmException e) {
            return ResultVoUtil.error("上传头像失败");
        }
    }

    /**
     * 保存上传的web格式图片
     */
    private ResultVo<?> saveFile(MultipartFile multipartFile, FileUpload upload) throws IOException, NoSuchAlgorithmException {
        // 判断是否为支持的图片格式
        /*
        String[] types = {
                "image/gif",
                "image/jpg",
                "image/jpeg",
                "image/png"
        };
        if(!FileUploadUtil.isContentType(multipartFile, types)){
            throw new ResultException(UploadResultEnum.NO_FILE_TYPE);
        }
         */
        // 判断图片是否存在
        /*
        FileUpload uploadMd5 = uploadService.getByMd5(FileUploadUtil.getFileMd5(multipartFile));
        if (uploadMd5 != null) {
            return ResultVoUtil.successZero(uploadMd5);
        }
        */
        FileUploadUtil.transferTo(multipartFile, upload);
        // 将文件信息保存到数据库中
        uploadService.save(upload);
        return ResultVoUtil.successZero(upload);
    }

    /**
     * 指向文件上传页面，需传递相关参数
     * @param refId 附件关联ID,表单尚未创建时随机给FileUpload refId默认赋值ID(ramId)，保存时再替换(当refId)
     * @param type 附件类型
     * @param fileType 附件限制上传的附件类型（如限制上传类型则不为空）: images（图片）、file（所有文件）、video（视频）、audio（音频）
     * @param path 附件上传的目录
     * @param filenum 允许上传的附件数量
     * @param model
     * @return
     */
    @GetMapping("/fileUpload") //@RequiresPermissions("system:dict:status")
    public String fileUpload(String refId, String type, String fileType, String path, int filenum, Model model) {
        if (StringUtils.isNotEmpty(refId)) model.addAttribute("refId" , refId);
        if (StringUtils.isNotEmpty(type)) model.addAttribute("type" , type);
        if (StringUtils.isNotEmpty(fileType)) model.addAttribute("fileType" , fileType);
        if (StringUtils.isNotEmpty(path)) model.addAttribute("path" , path);
        if (filenum > 0) model.addAttribute("filenum" , filenum);
        return "/base/fileUpload";
    }
    /**
     * 根据图片路径显示或返回图片路径
     */
    @PostMapping("/upload/showImage") @ResponseBody
    public ResultVo<?> showImage( @RequestParam("path") String path) {
        UploadProjectProperties properties = SpringContextUtil.getBean(UploadProjectProperties.class);
        FileSystemResource fsr = new FileSystemResource(properties.getFilePath() + path);
        File file = fsr.getFile();
        return ResultVoUtil.success();
    }

    /**
     * 下载附件
     * @param fileId
     * @param fileUrl
     * @param fileName
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "downloadFile") @ResponseBody
    public void downloadFile(String fileId, String filePath, String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (StringUtils.isEmpty(filePath)) filePath = request.getParameter("filePath");//为空从request中获取
        if (StringUtils.isEmpty(fileName)) fileName = request.getParameter("fileName");//为空从request中获取
        if (StringUtils.isEmpty(fileId) && StringUtils.isEmpty(filePath) && StringUtils.isEmpty(fileName)) return ;
        if (StringUtils.isNotEmpty(fileId)) {
            FileUpload fu = uploadService.getById(fileId);
            filePath = fu.getPath();
            if (StringUtils.isEmpty(fileName)) fileName = fu.getName();
        }
        String path = FileUploadUtil.getAllPath(null, filePath);
        if (StringUtils.isNotEmpty(path)) FileUploadUtil.download(response, path, fileName);
    }

}
